package iotwisp.base.util;

import java.io.StringWriter;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.XStreamException;
import com.thoughtworks.xstream.io.xml.DomDriver;

/**
 * @description: xml与bean转换工具类
 * @author: lidong
 * @author 2018年12月30日
 */
public class XstreamUtils {

	/**
	 * @param obj
	 * @return
	 */
	public static String beanToXml(Object obj) {
		if (obj == null)
			return null;
		XStream xstream;
		xstream = new XStream(new DomDriver("UTF-8"));
		xstream.autodetectAnnotations(true);
		xstream.processAnnotations(obj.getClass());
		StringWriter writer = new StringWriter();
		xstream.toXML(obj, writer);
		return "<?xml version='1.0' encoding='utf-8'?>\n" + writer.toString();
	}

	/**
	 * @param rawxml
	 * @param cls
	 * @return
	 * @throws XStreamException
	 */
	@SuppressWarnings("unchecked")
	public static <T> T xmlToBean(String rawxml, Class<T> cls) throws XStreamException {
		if (rawxml == null || "".equals(rawxml)) {
			return null;
		}
		XStream xstream;
		xstream = new XStream(new DomDriver("UTF-8"));
		// 忽略多余节点
		xstream.ignoreUnknownElements();
		xstream.autodetectAnnotations(true);
		xstream.processAnnotations(cls);
		T obj = (T) xstream.fromXML(rawxml);
		return obj;
	}

}